<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="新闻分类">
        <el-select
          v-model="searchForm.category"
          placeholder="请选择分类"
          clearable
          @clear="handleSearch"
        >
        <template v-for="item in categories">
          <el-option
            v-if="item.delFlag == 1"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </template>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column type="index" />
      <el-table-column prop="title" label="标题" min-width="200"/>
      <!-- 修改分类列显示 -->
      <el-table-column label="分类" width="150">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.category) }}
        </template>
      </el-table-column>
      
      <!-- 新增作者列 -->
      <el-table-column prop="author" label="作者" width="120"/>
      
      <!-- 修改阅读量字段 -->
      <el-table-column prop="views" label="阅读量" width="100" align="center"/>
      
      <!-- 修改发布时间字段及格式 -->
      <el-table-column label="发布时间" width="180">
        <template slot-scope="scope">
          {{ formatTime(scope.row.publishTime) }}
        </template>
      </el-table-column>
      
      <!-- 新增状态列 -->
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.delFlag === 0 ? 'danger' : 'success'">
            {{ scope.row.delFlag === 0 ? '禁用' : '启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="230">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="showComments(scope.row)" plain
          >评论</el-button
          >
          <el-button size="mini" type="primary" @click="handleEdit(scope)" plain
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDel(scope)" plain>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 评论弹窗（移动到表格外部） -->
    <el-dialog
        title="评论列表"
        :visible.sync="commentDialogVisible"
        width="80%"
      >
        <el-table
          :data="currentComments"
          border
          max-height="500"
          v-loading="commentLoading"
          size="mini"
        >
          <el-table-column type="index" width="50" align="center" />
          <el-table-column prop="commentContent" label="评论内容" min-width="200" />
          <el-table-column prop="commentTime" label="评论时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.commentTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                plain
                @click="handleCommentDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
  </div>
</template>

<script>
import {getNewsCategoryList, getNewsList, getNewsComments, deleteNewsComment, setDeleteNews} from "@/api/index";
import {parseTime} from "@/utils/index";
export default {
  name: "NewsCategory",
  data() {
    return {
      searchForm: { 
        category: "" 
      },
      // 新闻分类数据
      categories: [],
      // 新增弹窗相关数据
      commentDialogVisible: false,
      commentLoading: false,
      currentComments: [],
      currentNewsId: null,
      // 更新后的表格数据
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 20,
      }
    };
  },
  mounted(){
    this.fetchData()
    this.fetchCategoryList()
  },
  filters: {
    timeFilter(value) {
      return parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}')
    }
  },
  methods: {
    fetchCategoryList(){
      getNewsCategoryList({
        isHot: ''
      }).then(res=>{
        this.categories = res
      })
    },
    // 分类名称转换方法
    getCategoryName(value) {
      const category = this.categories.find(item => item.id === value)
      return category ? category.categoryName : '未知分类'
    },
    
    // 时间格式化方法
    formatTime(timestamp) {
      return timestamp ? new Date(timestamp).toLocaleString() : '-'
    },
    
    // 显示评论弹窗方法
    async showComments(row) {
      this.currentNewsId = row.id
      this.commentLoading = true
      this.commentDialogVisible = true
      // 模拟加载评论数据
      getNewsComments({
        newsId: row.id,
        pageNum: 1,
        count: 999
      }).then(res=>{
        this.currentComments = res.list
        this.commentLoading = false
      })
    },
    
    // 评论删除方法
    handleCommentDelete(commentId) {
      this.$confirm('确认删除该评论吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteNewsComment({
          id: commentId
        }).then(res=>{
          this.$message.success('删除成功')
          this.showComments({id: this.currentNewsId})
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.fetchData()
    },
    handleAdd() {
      // 跳转到新闻编辑页面（新增模式）
      this.$router.push({
        path: "/news/add",
        query: {
          mode: 'create' // 可选的模式标识
        }
      });
    },
    handleEdit(scope) {
      // 添加参数
      this.$router.push({
        path: "/news/add",
        query: {
          id: scope.row.id, // 传递当前行ID
        },
      });
    },
    handleSizeChange(val) {
      this.pagination.size = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.fetchData();
    },
    fetchData() {
      // 这里添加实际数据获取逻辑
      getNewsList({
        pageNum: this.pagination.current,
        count: this.pagination.size,
        category: this.searchForm.category
      }).then(res => {
        this.tableData = res.list
        this.pagination.total = res.total
      })
    },
    // 新增删除确认方法
    handleDel(scope) {
      this.$confirm("确认删除这条新闻吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          setDeleteNews({
            id: scope.row.id,
          }).then(res => {
            this.$message.success("删除成功！");
            this.fetchData(); // 删除后刷新数据
          })
        })
    },
  },
};
</script>

<style scoped>
.demo-form-inline {
  padding: 10px;
  background: #f8f8f8;
  border-radius: 4px;
}
</style>
